//
//  FamilyCallViewController.m
//  Cunli
//
//  Created by 湛亚 on 15/8/3.
//  Copyright (c) 2015年 lilubin. All rights reserved.
//

#import "FamilyCallViewController.h"
#import "MyDataService.h"
#import "NSString+MD5.h"
#import "UIImageView+WebCache.h"
#import "AddFamilyCallViewController.h"
#import "FamilyInfo.h"
#import "MediatorViewController.h"
#import "FamilyHotlineViewController.h"
#import "TongXunLu.h"
#import "LawyerViewController.h"
#import "UIColor+Addition.h"

#define SCREEN_WIDTH ([UIScreen mainScreen].bounds.size.width)
#define SCREEN_HEIGHT ([UIScreen mainScreen].bounds.size.height)

@interface FamilyCallViewController ()<UIAlertViewDelegate>{
    
    UILabel *tiShiLabel;
    UIScrollView *familyPicScrollView;
    NSMutableArray *familyArray;
    int currentCount;
    FamilyInfo *ChooseFamily;
    float picWidth,headImgWidth,headTapWidth;
}

@end

@implementation FamilyCallViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.title = @"亲情热线";
    familyArray=[[NSMutableArray alloc]init];
    currentCount=0;
    picWidth=140*(SCREEN_WIDTH/320.0);
    headImgWidth=70*(SCREEN_WIDTH/320.0);
    headTapWidth=(SCREEN_WIDTH-headImgWidth*3)/4.0;
    
    self.orSendRequest=NO;
    self.view.backgroundColor=[UIColor whiteColor];
    [self addView];
    [self getFamilyListInfo];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dontSendRequest) name:@"orSendRequest" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sendRequest) name:@"orSendRequest1" object:nil];
    
    if (![[NSUserDefaults standardUserDefaults]objectForKey:@"tongXunLuArray"]) {
        NSLog(@"本地无字典");
        [self getTongXunLuInfo];
    }
    
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"orSendRequest" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"orSendRequest1" object:nil];
}

- (void)dontSendRequest{
    
    self.orSendRequest=NO;
}

- (void)sendRequest{
    
    self.orSendRequest=YES;
}

-(void)addView{
    
    UIImageView *familyImgView=[[UIImageView alloc]initWithFrame:CGRectMake(15, 20, SCREEN_WIDTH-30,picWidth)];
    familyImgView.image=[UIImage imageNamed:@"hotlinebg1.png"];
    [self.view addSubview:familyImgView];
    
    tiShiLabel=[[UILabel alloc]initWithFrame:CGRectMake(30, picWidth+30, SCREEN_WIDTH-60, 30)];
    tiShiLabel.text=@"很抱歉,您还未添加亲人联系方式";
    tiShiLabel.textAlignment=1;
    [self.view addSubview:tiShiLabel];
    
    familyPicScrollView=[[UIScrollView alloc]initWithFrame:CGRectMake(0,picWidth+70, SCREEN_WIDTH, headImgWidth+50)];
    familyPicScrollView.showsHorizontalScrollIndicator=NO;
    [self.view addSubview:familyPicScrollView];
    
    UIButton *addFamilyBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    addFamilyBtn.frame=CGRectMake(70,picWidth+headImgWidth+140, SCREEN_WIDTH-140, 35);
    [addFamilyBtn addTarget:self action:@selector(addFamilyClick) forControlEvents:UIControlEventTouchUpInside];
    addFamilyBtn.backgroundColor=[UIColor convertHexColorToUIColor:0xc93336];
    addFamilyBtn.layer.cornerRadius =3.0;
    [addFamilyBtn setTitle:@"添加亲人" forState:UIControlStateNormal];
    [self.view addSubview:addFamilyBtn];
}

-(void)addFamilyClick{
    
    AddFamilyCallViewController *addVC=[[AddFamilyCallViewController alloc]init];
    addVC.orRefresh=YES;
    addVC.familyArr=familyArray;
    addVC.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:addVC animated:YES];
}

-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    if (self.orSendRequest==YES) {
        [self getFamilyListInfo];
        self.orSendRequest=NO;
    }
}

-(void)getFamilyListInfo{
    
    NSMutableDictionary *CheckParams =[[NSMutableDictionary alloc]init];
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
    [CheckParams setObject:resultSign forKey:@"sign"];
    [MyDataService requestURL:@"own_relativelist.php" httpMethod:@"GET" params:CheckParams fileDatas:nil complection:^(id result) {
        
        NSLog(@"%@",result);
        
        if (![[result objectForKey:@"response"] isEqualToString:@"own_relativelist"]) {
            
            MBProgressHUD *hud = [Config createHUD];
            hud.mode = MBProgressHUDModeCustomView;
            hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"error"]];
            hud.labelText = @"获取亲人列表失败!";
            [hud hide:YES afterDelay:1];
            return ;
        }
        
        NSMutableArray *arr=[result objectForKey:@"list"];
        //移除上次控件
        [familyPicScrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
        [familyArray removeAllObjects];
        
        if (arr.count>0) {
            
            tiShiLabel.text=@"长按头像可删除";
            tiShiLabel.font=[UIFont systemFontOfSize:15];
            tiShiLabel.textColor=[UIColor grayColor];
            
            familyPicScrollView.contentSize=CGSizeMake((headImgWidth+headTapWidth)*arr.count+headTapWidth, familyPicScrollView.frame.size.height);
            
            for (int i=0; i<arr.count; i++) {
                
                //FamilyInfo *family=[[FamilyInfo alloc]initWithDictionary:[arr objectAtIndex:i]];
                FamilyInfo *family=[FamilyInfo yy_modelWithDictionary:[arr objectAtIndex:i]];
                [familyArray addObject:family];
                
                UIImageView *picImgView=[[UIImageView alloc]initWithFrame:CGRectMake(headTapWidth+(headImgWidth+headTapWidth)*i, 10, headImgWidth, headImgWidth)];
                picImgView.layer.cornerRadius = headImgWidth/2.0;
                picImgView.clipsToBounds = YES;
                picImgView.userInteractionEnabled=YES;
                picImgView.tag=i;
                [picImgView setImageWithURL:[NSURL URLWithString:family.pic] placeholderImage:[UIImage imageNamed:@"default_touxiang.png"]];
                [familyPicScrollView addSubview:picImgView];
                //头像点击事件
                UITapGestureRecognizer *headImgTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(goToDetailInfo:)];
                [picImgView addGestureRecognizer:headImgTap];
                //头像长按事件
                UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
                longPress.minimumPressDuration =0.8; //定义按的时间
                [picImgView addGestureRecognizer:longPress];
                
                UILabel *nameLab=[[UILabel alloc]initWithFrame:CGRectMake(picImgView.frame.origin.x, picImgView.frame.size.height+10, headImgWidth, 30)];
                nameLab.text=family.truename;
                nameLab.font=[UIFont systemFontOfSize:15];
                nameLab.textAlignment=1;
                [familyPicScrollView addSubview:nameLab];
            }
            
        }else{
            
            tiShiLabel.text=@"很抱歉,您还未添加亲人联系方式";
            tiShiLabel.textColor=[UIColor blackColor];
            tiShiLabel.font=[UIFont systemFontOfSize:17];
        }
        
    }failureAction:^{
        
    }];
}

-(void)longPress:(UILongPressGestureRecognizer *)gestureRecognizer{
    
    //NSLog(@">>>>>>>>>>>>>>长按按钮%d",gestureRecognizer.view.tag);
    ChooseFamily=[familyArray objectAtIndex:gestureRecognizer.view.tag];
    NSString *alertIntroduce=[NSString stringWithFormat:@"确定删除%@吗?",ChooseFamily.truename];
    if ([gestureRecognizer state] == UIGestureRecognizerStateBegan) {
        
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示" message:alertIntroduce delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"删除", nil];
        [alert show];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    if (buttonIndex==0) {
        return;
    }else{
        [self delectFamilyInfoWithItemid:ChooseFamily.itemid];
    }
}

-(void)delectFamilyInfoWithItemid:(NSString *)itemid{
    
    NSMutableDictionary *CheckParams =[[NSMutableDictionary alloc]init];
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
    [CheckParams setObject:itemid forKey:@"itemid"];
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
    [CheckParams setObject:resultSign forKey:@"sign"];
    [MyDataService requestURL:@"del_own_relative.php" httpMethod:@"GET" params:CheckParams fileDatas:nil complection:^(id result) {
        
        NSLog(@"%@",result);
        
        MBProgressHUD *hud = [Config createHUD];
        hud.mode = MBProgressHUDModeCustomView;
        if ([[result objectForKey:@"response"] isEqualToString:@"del_own_relative"]) {
            
            hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"done"]];
            hud.labelText = @"删除成功!";
            [hud hide:YES afterDelay:1];
            [self getFamilyListInfo];
            
        }else{
            
            hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"error"]];
            hud.labelText = @"删除失败!";
            [hud hide:YES afterDelay:1];
        }
        
    }failureAction:^{
        
    }];
}

-(void)goToDetailInfo:(UIGestureRecognizer *)btn{
    
        FamilyInfo *family=[familyArray objectAtIndex:btn.view.tag];
        LawyerViewController *familyVC=[[LawyerViewController alloc]init];
        familyVC.touserid=family.userid;
        familyVC.hidesBottomBarWhenPushed=YES;
        [self.navigationController pushViewController:familyVC animated:YES];
}

-(void)getTongXunLuInfo{
    
    NSMutableDictionary *CheckParams =[[NSMutableDictionary alloc]init];
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
    [CheckParams setObject:[Config getOwnAreaids] forKey:@"areaids"];
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
    [CheckParams setObject:resultSign forKey:@"sign"];
    [MyDataService requestURL:@"addressbook_v1.php" httpMethod:@"GET" params:CheckParams fileDatas:nil complection:^(id result) {
        
        NSLog(@"%@",result);
        
        if ([[result objectForKey:@"response"] isEqualToString:@"addressbook_v1"]) {
            
            NSDictionary *dataDic=[result objectForKey:@"data"];
            NSArray *listArray=[dataDic objectForKey:@"list"];
            
            if (listArray.count>0) {
                
                NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
                [userDefault setObject:listArray forKey:@"tongXunLuArray"];
                [userDefault synchronize];
            }
            
        }
        
    }failureAction:^{
        
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
